//
//  WBMainViewController.swift
//  SilenceWeibo
//
//  Created by admin on 2017/6/19.
//  Copyright © 2017年 honliv. All rights reserved.
//

import UIKit

//主控制器
class WBMainViewController: UITabBarController {
    
    //定时器
    fileprivate var timer:Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupChildController()
        setupComposeButton()
        setupTimer()
        
        //设置代理
        delegate = self;
        
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
    }
    
    deinit {
        //销毁时钟
        timer?.invalidate()
        NotificationCenter.default.removeObserver(self)
    }
    
    
    /**
     portrait   : 竖屏：肖像
     landspace  : 横屏：风景画
     - 使用代码控制设备的方向，好处：可以再需要横屏的时候，单独处理
     - 设置支持的方向之后，当前的控制器及子控制器都会遵守这个方向
     - 如果播放视频，通常是通过modal展现的！
     */
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return .portrait
    }
    //MARK: - 监听方法
    
    @objc fileprivate func userLogin(n: Notification){
        print("用户登录通知\(n)")
        //展现登录控制器 - 通常会和 UINavigationController 连用 方便返回
        
        let nav = UINavigationController(rootViewController: WBOAuthViewController())
        
        present(nav, animated: true, completion: nil)
    }
    
    //撰写微博
    //FIXME: 没有实现
    //fileprivate 能够保证放在私有，仅在当前对象被访问
    //@objc 允许这个函数在运行时通过OC的消息机制被调用！
    @objc fileprivate func composeStatus(){
        print("撰写微博")
        
        //测试方向旋转
        let vc = UIViewController()
        vc.view.backgroundColor = UIColor.cz_random()
        vc.title = "测试横屏"
        let nav = UINavigationController(rootViewController: vc)
        
        present(nav, animated: true, completion: nil)
    }
    
    
    //MARK: - 私有控件
    //撰写按钮
    fileprivate lazy var composeButton:UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    
}

// MARK: - UITabBarControllerDelegate
extension WBMainViewController:UITabBarControllerDelegate{
    
    /// 将要选择tabBariems
    ///
    /// - Parameters:
    ///   - tabBarController: <#tabBarController description#>
    ///   - viewController: 目标控制器
    /// - Returns: 是否切换到目标控制器
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        print("将要切换到\(viewController)")
        
        //1> 获取控制器在数组中的索引
        let idx = childViewControllers.index(of: viewController)
        //2> 判断当前索引是首页，同时点击的也是首页按钮
        if selectedIndex == 0 && idx == selectedIndex {
            print("点击首页")
            
            //3> 让表格滚动到顶部
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! WBHomeViewController
            
            vc.tableView?.setContentOffset(CGPoint(x:0, y:-64), animated: true)
            
            //4> 刷新数据
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                vc.loadData();
            })
        }
        
        return !viewController.isMember(of: UIViewController.self)
    }
}

// MARK: - 时钟相关方法
extension WBMainViewController{
    /// 定义时钟,建议时间设置的长一些
    fileprivate func setupTimer(){
        timer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    
    /// 时钟出发方法
    @objc func updateTimer(){
        
        if !WBNetworkManager.shared.userLogon{
            return
        }
        WBNetworkManager.shared.unreadCount { (count) in
            
//            print("检测到\(count)条新微博")
            
            //设置 首页 tabBarItem 的 badgeNumber
            self.tabBar.items?[0].badgeValue = count > 0 ? String(count) : nil
            //设置APP的badgeNumber
            UIApplication.shared.applicationIconBadgeNumber = count;
        }
    }
}




//extension 类似于OC中的分类,在Swift中还可以用来切分代码块
//可以把相近功能的函数，放在一个extension中
//便于代码维护
//注意：和 OC的分类一样，extension中不能定义属性

extension WBMainViewController{
    
    fileprivate func setupComposeButton(){
        tabBar.addSubview(composeButton)
        
        //计算按钮的宽度
        let count = CGFloat(childViewControllers.count)
        
        //将向内缩进的宽度减少，能够让按钮的宽度变大，盖住容错点，防止穿帮！
        let w = tabBar.bounds.width / count
        
        //CGRectInset 正数向内缩进，负数向外扩展
        composeButton.frame = tabBar.bounds.insetBy(dx: w * 2, dy: 0)
        
        //按钮监听方法
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
    }
    
    //设置所有子控制器
    fileprivate func setupChildController(){
        
        //0.获取沙盒 json 路径
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        
        //加载 data
        var data = NSData(contentsOfFile: jsonPath)
        
        //判断 data 是否有内容，如果没有，说明本地沙盒没有文件
        if data == nil{
            //从Bundle加载data
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
        }
        //data 一定会有一个内容，反序列化
        //反序列化成数组
        guard let array = try?JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String:Any]]
            else{
                return
        }
        
        //遍历数组，循环创建控制器数组
        var arrayM = [UIViewController]()
        for dict in array! {
            arrayM.append(controller(dict: dict))
        }
        //设置 tabBar的子控制器
        viewControllers = arrayM
        
    }
    
    /// 使用字典创建一个子控制器
    ///
    /// - Parameter dic: 信息字典 [clsName,title,imageName,"visitorInfo"]
    /// - Returns: 子控制器
    private func controller(dict:[String:Any]) -> UIViewController{
        //1.取得字典内容
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type,
            let visitorDict = dict["visitorInfo"] as? [String:String]
            else{
                return UIViewController()
        }
        //2.创建视图控制器
        
        //1>将clsName 转换成cls
        let vc = cls.init()
        
        //设置控制器的访客信息字典
        vc.visitInfoDic = visitorDict
        
        vc.title = title
        //3.设置图像
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
        
        //4.设置tabbar的标题字体(颜色，大小)
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .highlighted)
        //系统默认是12号字，修改字体大小要设置Normal
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 12)], for: UIControlState.normal)
        
        //实例化导航控制器的时候，会调用 push 方法将rootVC压栈
        let nav = WBNavigationController(rootViewController: vc)
        
        return nav
    }
}
